package com.topisv.tms.web.work;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.hibernate.StaleObjectStateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.LogisticsCompanyService;
import com.topisv.tms.service.ResetOrderService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.tools.DataTablesUtils;
import com.topisv.tms.utils.DateUtils;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.web.base.BaseController;

import net.sf.json.JSONObject;

/**
 * 重接订单
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/v2_resetOrder")
public class ResetOrderController extends BaseController {
	private Logger log = LoggerFactory.getLogger(ResetOrderController.class);
	@Autowired
	private CustomersService customersService;

	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private LogisticsCompanyService logisticsCompanyService;
	@Autowired
	private EdiOrderService ediOrderService;
	@Autowired
	private ResetOrderService resetOrderService;

	/**
	 * 导向待处理订单页面
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "show")
	public String show(Model model, ServletRequest request) {
		try {
			// 查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList = this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList", customerList);
			// by zhangweize 增加快递公司
			model.addAttribute("logisticsList", logisticsCompanyService.findAll());

			// 如果是商家用户,初始化数据
			if (StatusEnums.user_type_customer.getStatus().equals(curUser.userType)) {
				String customerCode = customerList.get(0).getCustomerCode();
				model.addAttribute("customerCode", customerCode);
				// 初始化仓库数据
				List<AreaGroup> warehouseList = this.areaGroupService.loadAreaGroupByAuthority(curUser, customerCode);
				model.addAttribute("warehouseList", warehouseList);
			} else if (StatusEnums.user_type_paiu.getStatus().equals(curUser.userType)) {
				List<AreaGroup> warehouseList = areaGroupService.findByAreaGroups(curUser.areagroups);
				model.addAttribute("warehouseList", warehouseList);
			}
		} catch (Exception e) {
			log.error("error", e);
		}
		return "resetOrder/resetOrderList";
	}

	/**
	 * 需重接订单
	 * 
	 * @param params
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "queryResetOrder", method = RequestMethod.POST)
	public void queryResetOrder(@RequestBody JSONParam[] paramJson, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		try {
			// 变量定义
			PrintWriter out = response.getWriter();
			JSONObject json = new JSONObject();
			Page<EdiOrder> page = null;

			// 当前用户
			Map<String, Object> param = new HashMap<String, Object>();
			ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();

			// 客户端参数
			Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);
			String sEcho = paramMap.get("sEcho");
			int start = Integer.parseInt(paramMap.get("iDisplayStart"));
			int length = Integer.parseInt(paramMap.get("iDisplayLength"));
			String customerCode = paramMap.get("customerCode");
			String warehouseCode = paramMap.get("warehouseCode");
			String dataRange = paramMap.get("dataRange");
			String orderno = paramMap.get("orderno");
			String cacode = paramMap.get("cacode");
			// 封装查询参数
			if (StringUtils.isEmpty(customerCode)) { // 如果商家编码为空，赋予默认权限值
				String customerCodes = this.customersService.loadCustomerByAuthority(shiroUser.jobuuid);
				param.put("customerCodes", customerCodes);
			} else {
				param.put("customerCode", customerCode);
			}

			if (StringUtils.isEmpty(warehouseCode)) { // 如果仓库编码为空，赋予默认权限值
				String areagroups = shiroUser.areagroups;
				param.put("areagroups", areagroups);
			} else {
				param.put("warehouseCode", warehouseCode);
			}

			if (StringUtils.isNotEmpty(dataRange)) {
				Map<String, Date> dataMap = DateUtils.getDateRange(dataRange);
				Date fromDate = dataMap.get("fromDate");
				Date toDate = dataMap.get("toDate");
				param.put("fromDate", fromDate);
				param.put("toDate", toDate);
			}

			param.put("orderStatus", "ok");
			param.put("status", "pending");
			// 未分配的也显示出来
			param.put("dispatchFlag", "0");
			param.put("deliveryOrderType", "B2BCK");
			param.put("orderno", orderno);

			// by zhangweize 增加快递公司查询条件
			param.put("companyCode", cacode);

			// 查询
			int curPage = (start / length) + 1;
			page = resetOrderService.loadPageOrder(param, curPage, length);
			List<EdiOrder> eOrderList = page.getContent();

			// 封装查询结果
			json.put("aaData", eOrderList);
			json.put("sEcho", sEcho);
			json.put("iTotalRecords", page.getTotalElements());
			json.put("iTotalDisplayRecords", page.getTotalElements());

			out.print(json);

		} catch (Exception e) {

		}
	}

	/**
	 * 批量重接订单
	 * 
	 * @param customerCode
	 * @param warehouseCode
	 * @param ids
	 * @param dataRange
	 * @param response
	 */
	@RequestMapping(value = "batchReuse", method = RequestMethod.POST)
	public void batchReuse(@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "warehouseCode") String warehouseCode,
			@RequestParam(value = "dataRange") String dataRange, @RequestParam(value = "ids") String[] ids,
			HttpServletRequest request, HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		boolean isLockSuccess = false;
		int failCount = 0;
		try {
			out = response.getWriter();
			json = new JSONObject();
			Map<String, Date> dates = DateUtils.getDateRange(dataRange);
			// 根据商家、仓库进行加锁操作
			isLockSuccess = resetOrderService.lock(customerCode, warehouseCode, dates, getShiroUser().realname);
			if (!isLockSuccess) {
				json.put("status", "0");
				json.put("msg", "当前商家以及所属的仓库已在处理,请勿重复处理！");
				return;
			}
			// 进行重接订单操作
			for (String id : ids) {
				failCount = resetOrderService.reUseEdiOrder(id) == true ? failCount : (++failCount);
			}
			json.put("status", "1");
			json.put("msg", "共" + ids.length + "单,成功" + (ids.length - failCount) + ",失败" + failCount);
		} catch (Exception e) {
			log.error("批量重接订单异常:", e);
			json.put("status", "0");
			json.put("msg", "重接失败,请联系技术支持!");
		} finally {
			// 根据商家、仓库进行解锁操作
			if (isLockSuccess) {
				try{
					resetOrderService.unlock(customerCode, warehouseCode);
				}catch(Exception e) {
					json.put("status", "0");
					json.put("msg", "批量重接订单解锁异常!");
					log.error("批量重接订单解锁异常:", e);
				}
			}
			out.print(json.toString());
		}
	}

}
